package org.elephas.webapp.frontend.component.common;

import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;

import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.MarkupStream;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.IModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MultiLabel extends Label {
	private static final long serialVersionUID = 1L;
	
	private static final Logger logger = LoggerFactory
			.getLogger(MultiLabel.class);

	private static final String DEFAULT_SEPARATOR = ", ";

	public MultiLabel(String id) {
		super(id);
	}
	
	public MultiLabel(String id, IModel model) {
		super(id, model);
	}
	
	@Override
	protected void onComponentTagBody(MarkupStream markupStream,
			ComponentTag openTag) {
		Object object = getModelObject();
		if (object == null) {
			replaceComponentTagBody(markupStream, openTag, "");
		}
		
		StringBuffer sb = new StringBuffer();
		Iterator iter = getItemIterator(object);
		while (iter.hasNext()) {
			Object o = iter.next();
			if (o != null) {
				sb.append(renderObject(o));
			} else {
				logger.warn("did not render null value");
			}
			if (iter.hasNext()) {
				sb.append(getSeparator());
			}
		}
		replaceComponentTagBody(markupStream, openTag, sb.toString());
	} 
	
	private Iterator getItemIterator(Object object) {
		if (object instanceof Object[]) {
			return Arrays.asList((Object[]) object).iterator();
		}
		if (object instanceof Collection) {
			return ((Collection) object).iterator();
		}
		return Collections.singletonList(object).iterator();
	}

	
	protected String getSeparator() {
		return DEFAULT_SEPARATOR;
	}

	protected String renderObject(Object object) {
		return object.toString();
	}
	
	protected boolean renderNull() {
		return false;
	}
}
